import 'package:flutter/services.dart';
import 'package:flutter/material.dart';

///
/// 验证码输入框
///
class QCodeTextField extends StatefulWidget {
  final int maxLength;
  final TextEditingController numberController;
  final Function? callBack;
  final Widget rightWidget;
  final bool showClear; // 是否显示清除按钮

  const QCodeTextField({
    Key? key,
    required this.numberController,
    required this.rightWidget,
    this.maxLength = 6,
    this.showClear = true,
    this.callBack,
  }) : super(key: key);

  @override
  _QCodeTextFieldState createState() => _QCodeTextFieldState();
}

class _QCodeTextFieldState extends State<QCodeTextField> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: TextField(
            controller: widget.numberController,
            style: const TextStyle(fontSize: 17, color: Colors.black),
            keyboardType: TextInputType.number,
            inputFormatters: [
              LengthLimitingTextInputFormatter(widget.maxLength),
              FilteringTextInputFormatter.allow(RegExp("[0-9]"))
            ],
            decoration: const InputDecoration(
              isCollapsed: true, // 高度包裹
              border: InputBorder.none,
              hintText: '请输入验证码',
              hintStyle: TextStyle(
                fontSize: 16,
                color: Color.fromRGBO(153, 153, 153, 1),
              ),
            ),
            onChanged: (value) {
              setState(() {});
              if (widget.callBack != null) {
                widget.callBack!();
              }
            },
          ),
        ),
        widget.showClear
            ? Offstage(
                offstage: widget.numberController.text != '' ? false : true,
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      widget.numberController.text = '';
                    });
                    if (widget.callBack != null) {
                      widget.callBack!("");
                    }
                  },
                  child: Container(
                    height: 13,
                    width: 13,
                    margin: const EdgeInsets.only(right: 8),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: const Color.fromRGBO(161, 165, 169, 1),
                    ),
                    child: const Icon(
                      Icons.close_rounded,
                      size: 10,
                      color: Colors.white,
                    ),
                  ),
                ),
              )
            : Container(),
        widget.rightWidget
      ],
    );
  }
}
